package com.zlyx.easy.core.map;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.zlyx.easy.core.utils.JsonUtils;

/**
 * <p>
 * 等价于ConcurrentHashMap《String,V》》, 功能增强
 * </p>
 *
 * @author 赵光
 * @since 2020年1月10日
 */
public class ThreadMap<V> extends ConcurrentHashMap<String, V> {

	private static final long serialVersionUID = 1L;

	public ThreadMap() {

	}

	public ThreadMap<V> addValue(String key, V value) {
		put(key, value);
		return this;
	}

	public ThreadMap<V> addValue(Map<String, V> map) {
		putAll(map);
		return this;
	}

	public <R> R getValue(String key) {
		return getValue(key, null);
	}

	@SuppressWarnings("unchecked")
	public <R> R getValue(String key, R defaultValue) {
		if (containsKey(key)) {
			return (R) get(key);
		}
		return defaultValue;
	}

	public List<V> getValues() {
		return new ArrayList<>(values());
	}

	public boolean withoutKey(String key) {
		return !containsKey(key);
	}

	public boolean notEmpty() {
		return !isEmpty();
	}

	@Override
	public String toString() {
		return JsonUtils.toJson(this);
	}

	/**
	 * newMap
	 * 
	 * @param <V>
	 * @return
	 */
	public static <V> ThreadMap<V> newMap() {
		return new ThreadMap<>();
	}

	/**
	 * newMap
	 * 
	 * @param <V>
	 * @param key
	 * @param value
	 * @return
	 */
	public static <V> ThreadMap<V> newMap(String key, V value) {
		return new ThreadMap<V>().addValue(key, value);
	}

	/**
	 * newMap
	 * 
	 * @param <V>
	 * @param map
	 * @return
	 */
	public static <V> ThreadMap<V> newMap(Map<String, V> map) {
		return new ThreadMap<V>().addValue(map);
	}
}
